package com.authoritydemo.controller;

import com.authoritydemo.entity.Users;
import com.authoritydemo.service.UsersService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {

    @Autowired
    private UsersService usersService;

    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session) {
        Users user = usersService.getOne(new QueryWrapper<Users>()
                .eq("username", username)
                .eq("password", password));

        if (user != null) {
            session.setAttribute("user", user);
            return "redirect:/index.html";
        } else {
            return "login";
        }
    }

    @GetMapping("/api/user/info")
    @ResponseBody
    public Map<String, Object> getUserInfo(HttpSession session) {
        Users user = (Users) session.getAttribute("user");
        Map<String, Object> result = new HashMap<>();
        if (user != null) {
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", user);
        } else {
            result.put("code", 401);
            result.put("message", "未登录");
        }
        return result;
    }
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "login";
    }
}